package com.fadadianqi.mall.service;

import com.fadadianqi.commons.PrimaryKeyCreator;
import com.fadadianqi.mall.dao.OrderItemDAO;
import com.fadadianqi.mall.dao.OrdersDAO;
import com.fadadianqi.mall.orders.model.OrderItem;
import com.fadadianqi.mall.orders.model.Orders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

/**
 * Created by LightHuangfu
 * User: LightHuangfu
 * Date: 14-2-25
 * Time: 下午10:17
 */
@Service
public class OrderService {


    @Autowired
    private OrdersDAO ordersDAO;

    @Autowired
    private OrderItemDAO orderItemDAO;

    /**
     * 创建一条订单并且同时添加一条产品进入这个订单
     * <p/>
     * 这个方法应该是用户在第一次下单的时候使用
     *
     * @param customerId
     * @param productId
     * @param price
     */
    public void createOrder(String customerId, String productId, double price) {
        String orderId = PrimaryKeyCreator.create();
        Orders orders = new Orders();
        orders.setAddTime(new Timestamp(System.currentTimeMillis()));
        orders.setCustomerId(customerId);
        orders.setSoldPrice(price);
        orders.setId(orderId);
        ordersDAO.create(orders);
        OrderItem orderItem = new OrderItem();
        orderItem.setOrdersId(orders.getId());
        orderItem.setProductId(productId);
        orderItem.setSoldPrice(price);
        orderItem.setId(PrimaryKeyCreator.create());
        orderItemDAO.create(orderItem);
    }

    /**
     * 添加一条新的产品到已经存在的订单中，相当于用户点击了继续购买之后的行为
     *
     * @param orderId
     * @param productId
     * @param price
     */
    public void addOrderItem(String orderId, String productId, double price) {
        OrderItem orderItem = new OrderItem();
        orderItem.setOrdersId(orderId);
        orderItem.setProductId(productId);
        orderItem.setSoldPrice(price);
        orderItem.setId(PrimaryKeyCreator.create());
        orderItemDAO.create(orderItem);
    }

    public void removeOrderItem(String orderItemId) {
        orderItemDAO.removeOrderItem(orderItemId);
    }

    public void removeOrder(String id) {
        ordersDAO.removeById(id);
    }

    public void remove(String orderItemId, String orderId) {
        removeOrderItem(orderItemId);
        removeOrder(orderId);
    }
}
